package com.lzb.randomturntable.fragment;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;

import com.lzb.basic.utils.SPUtil;
import com.lzb.randomturntable.BaseNoModelFragment;
import com.lzb.randomturntable.Content;
import com.lzb.randomturntable.R;
import com.lzb.randomturntable.bean.CoinBean;
import com.lzb.randomturntable.databinding.FragmentGuessBinding;
import com.lzb.randomturntable.dialog.CoinSettingDialog;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link GuessFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class GuessFragment extends BaseNoModelFragment<FragmentGuessBinding> implements View.OnClickListener {

    private List<CoinBean> listCoin = new ArrayList<>();
    private boolean isCurrentlyHeads; // 当前显示的是正面还是反面
    private long flipInterval = 70; // 翻转间隔时间（毫秒）
    private boolean isFlipping = false;
    private int selPosition;
    private Handler flipHandler;
    private Runnable flipRunnable;
    private int frontNum, reverseNum;


    @Override
    protected int onCreate() {
        return R.layout.fragment_guess;
    }

    @Override
    protected void initView() {
        mDataBinding.ivSetting.setOnClickListener(this);
        mDataBinding.ivRefresh.setOnClickListener(this);
        mDataBinding.tvToss.setOnClickListener(this);

        flipHandler = new Handler();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ivSetting) {//硬币设置
            showCoinSettingDialog();
        } else if (id == R.id.ivRefresh) {//刷新
            frontNum = 0;
            reverseNum = 0;
            SPUtil.putInt(mContext, Content.frontNum, frontNum);
            SPUtil.putInt(mContext, Content.reverseNum, reverseNum);
            mDataBinding.tvFrontNum.setText(frontNum + "");
            mDataBinding.tvReverseNum.setText(reverseNum + "");
        } else if (id == R.id.tvToss) {//抛硬币
            flipCoin();
        }
    }

    @Override
    protected void initData() {
        listCoin.add(new CoinBean(R.drawable.yb1, R.drawable.yb2));
        listCoin.add(new CoinBean(R.drawable.yb3, R.drawable.yb4));
        listCoin.add(new CoinBean(R.drawable.yb5, R.drawable.yb6));
        listCoin.add(new CoinBean(R.drawable.yb7, R.drawable.yb8));
        selPosition = SPUtil.getInt(mContext, Content.coinPos, 0);
        frontNum = SPUtil.getInt(mContext, Content.frontNum, 0);
        reverseNum = SPUtil.getInt(mContext, Content.reverseNum, 0);
        mDataBinding.tvFrontNum.setText(frontNum + "");
        mDataBinding.tvReverseNum.setText(reverseNum + "");
        setData();
    }

    private void setData() {
        mDataBinding.ivCoin.setImageResource(isCurrentlyHeads ? listCoin.get(selPosition).getFrontImg() : listCoin.get(selPosition).getReverseImg());
        mDataBinding.ivFront.setImageResource(listCoin.get(selPosition).getFrontImg());
        mDataBinding.ivReverse.setImageResource(listCoin.get(selPosition).getReverseImg());
    }

    private void flipCoin() {
        isFlipping = true;
        mDataBinding.tvToss.setEnabled(false);
        Random random = new Random();
        isCurrentlyHeads = random.nextBoolean(); // 随机开始的一面
        mDataBinding.ivCoin.setImageResource(isCurrentlyHeads ? listCoin.get(selPosition).getFrontImg() : listCoin.get(selPosition).getReverseImg());

        // 总动画时间
        long totalDuration = 2500;

        // 创建向上移动动画 - 抛物线轨迹的上半部分
        TranslateAnimation upAnimation = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, -2f // 向上移动2倍自身高度
        );
        long upDuration = totalDuration / 2;
        upAnimation.setDuration(upDuration);
        upAnimation.setInterpolator(new DecelerateInterpolator(1.5f)); // 减速上抛

        // 创建向下移动动画 - 抛物线轨迹的下半部分
        TranslateAnimation downAnimation = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 2f // 向下移动2倍自身高度
        );
        long downDuration = totalDuration / 2;
        downAnimation.setDuration(downDuration);
        downAnimation.setInterpolator(new AccelerateInterpolator(1.5f)); // 加速下落
        downAnimation.setStartOffset(upDuration); // 在上抛动画结束后开始

        // 设置硬币翻转的Runnable
        flipRunnable = new Runnable() {
            @Override
            public void run() {
                if (isFlipping) {
                    // 切换正反面
                    isCurrentlyHeads = !isCurrentlyHeads;
                    mDataBinding.ivCoin.setImageResource(isCurrentlyHeads ? listCoin.get(selPosition).getFrontImg() : listCoin.get(selPosition).getReverseImg());
                    // 继续翻转
                    flipHandler.postDelayed(this, flipInterval);
                }
            }
        };

        // 组合完整动画
        AnimationSet animationSet = new AnimationSet(true);
        animationSet.addAnimation(upAnimation);
        animationSet.addAnimation(downAnimation);

        animationSet.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                // 开始翻转硬币
                flipHandler.post(flipRunnable);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                // 停止翻转
                flipHandler.removeCallbacks(flipRunnable);
                isFlipping = false;

                // 随机决定最终的正反面
                boolean isHeads = random.nextBoolean();
                mDataBinding.ivCoin.setImageResource(isHeads ? listCoin.get(selPosition).getFrontImg() : listCoin.get(selPosition).getReverseImg());
                if (isHeads) {
                    frontNum++;
                    SPUtil.putInt(mContext, Content.frontNum, frontNum);
                    mDataBinding.tvFrontNum.setText(frontNum + "");
                } else {
                    reverseNum++;
                    SPUtil.putInt(mContext, Content.reverseNum, reverseNum);
                    mDataBinding.tvReverseNum.setText(reverseNum + "");
                }
                mDataBinding.tvToss.setEnabled(true);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });

        mDataBinding.ivCoin.startAnimation(animationSet);
    }

    private void showCoinSettingDialog() {
        CoinSettingDialog dialog = new CoinSettingDialog(mContext);
        dialog.setListener(new CoinSettingDialog.Ilistener() {
            @Override
            public void clickItem() {
                selPosition = SPUtil.getInt(mContext, Content.coinPos, 0);
                setData();
            }
        });
        dialog.show();
    }

}